package com.jldx.oa.controller;

import java.util.Date;

import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jldx.common.Result;
import com.jldx.oa.bean.User;

public class UserController extends BaseController{

	public void index(){
		render("/WEB-INF/views/user.html");
	}
	
	public void query(){
		Integer pageNumber = getPage();
		String name = getPara("name");
		Integer limit = getLimit();
		Kv cond = Kv.by("name", name);
		SqlPara sqlPara = Db.getSqlPara("oa.userList",cond);
		Page<User> page = User.dao.paginate(pageNumber, limit, sqlPara);
		Result result = Result.cast(page);
		renderJson(result);
	}
	
	public void edit(){
		Integer id = getParaToInt("id");
		if(id!=null){
			User user = User.dao.findById(id);
			setAttr("user", user);
		}
		view("user_edit.html");
	}
	
	public void save(){
		User user = getModel(User.class,"");
		if(user.getId()!=null){
			user.update();
		}else{
			user.setRegTime(new Date());
			user.save();
		}
		renderText("suc");
	}
	
	public void delete(){
		Integer id = getParaToInt("id");
		if(id!=null){
			User.dao.deleteById(id);
		}
		renderText("suc");
	}
	
	public void changeState(){
		Integer id = getParaToInt("id");
		String state = getPara("state");
		
		Db.update("update user set state = ? where id = ?",id,state);
		renderText("suc");
	}
	
	public void toChangePassword(){
		view("chanage_password.html");
	}
	
	public void changePassword(){
		String oldPassword = getPara("oldPassword");
		String newPassword = getPara("newPassword");
		String confirmPassword = getPara("confirmPassword");
		
		User user = getCurrentUser();
		if(!user.getPassword().equals(oldPassword)){
			setAttr("msg", "旧密码错误！");
		}else if(!newPassword.equals(confirmPassword)){
			setAttr("msg", "新密码和确认密码不一致！");
		}else{
			Db.update("update user set password = ? where id = ?",newPassword,user.getId());
			setAttr("msg", "修改成功！");
		}
		view("chanage_password.html");
	}
	
	public void mreg(){
		User user = getModel(User.class,"");
		user.setRegTime(new Date());
		user.setType("user");
		user.save();
		renderText("suc");
	}
	
	public void mlogin(){
		String username = getPara("username");
		String password = getPara("password");
		User user = User.dao.findFirst("select * from user where username = ? and password = ?",username,password);
		if(user!=null){
			System.out.println("login suc ..");
			setSessionAttr("lg_user", user);
			renderText("suc");
			System.out.println("login suc.");
		}else{
			System.out.println("login fail.");
			renderText("fail");
		}
	}
}
